<template>
  <div id="app">
    <el-header height="60px" class="header">
      <div class="header-content">
        <div class="title">“食易通”餐厅点餐系统</div>
        <div class="user-actions">
          <el-button type="primary" @click="goToLogin" class="login-button" v-if="!isLoggedIn">登录</el-button>
          <el-button type="success" @click="LoginOut" class="login-button" v-if="isPerson">退出登录</el-button>
          <el-button type="success" @click="goToPerson" class="login-button"
            v-if="isPerson">{{this.username}}</el-button>
          <el-button @click="goToAdmin">后台管理</el-button>
        </div>
      </div>
    </el-header>

    <el-main>
      <div class="content">
        <el-aside width="260px" class="categories">
          <div class="category-header">
            <h3 class="category-title">菜品分类</h3>
          </div>
          <el-tabs v-model="activeTabName" tab-position="left" class="custom-tabs">
            <el-tab-pane label="🔥 推荐" name="recommend">
              <el-menu :default-active="recommendActiveIndex" @select="handleSelect('recommend',$event)" class="custom-menu">
                <el-menu-item index="1" class="menu-item-modern">🍜 风味小吃</el-menu-item>
                <el-menu-item index="2" class="menu-item-modern">🍳 特色小炒</el-menu-item>
                <el-menu-item index="3" class="menu-item-modern">🍰 饭后甜点</el-menu-item>
                <el-menu-item index="4" class="menu-item-modern">🍚 主食专区</el-menu-item>
                <el-menu-item index="5" class="menu-item-modern">🥤 冰爽饮品</el-menu-item>
              </el-menu>
            </el-tab-pane>
            <el-tab-pane label="✨ 最新" name="new">
              <el-menu :default-active="newActiveIndex" @select="handleSelect('new',$event)" class="custom-menu">
                <el-menu-item index="1" class="menu-item-modern">🆕 新品上市</el-menu-item>
                <el-menu-item index="2" class="menu-item-modern">⭐ 经典复刻</el-menu-item>
              </el-menu>
            </el-tab-pane>
            <el-tab-pane label="🌟 热门" name="hot">
              <el-menu :default-active="hotActiveIndex" @select="handleSelect('hot',$event)" class="custom-menu">
                <el-menu-item index="1" class="menu-item-modern">🔥 热销套餐</el-menu-item>
                <el-menu-item index="2" class="menu-item-modern">💎 推荐套餐</el-menu-item>
              </el-menu>
            </el-tab-pane>
          </el-tabs>
        </el-aside>
        <div class="food-area">
          <div class="search-and-payment">
            <div class="search-bar-container">
              <el-input v-model="searchQuery" placeholder="搜索菜品" class="search-bar">
                <template #append>
                  <el-button icon="el-icon-search" @click="search"></el-button>
                </template>
              </el-input>
              <el-button type="info" icon="el-icon-refresh" @click="resetSearch" class="reset-button">重置</el-button>
            </div>
            <div class="button-container">
              <el-button type="warning" class="cart-button" icon="el-icon-shopping-cart-full"
                @click="toggleCart">购物车</el-button>
              <el-drawer title="购物车" :visible.sync="isCartVisible" direction="rtl" size="30%">
                <div class="cart-content">
                  <el-list>
                    <el-list-item v-for="(item, index) in cart" :key="index" class="cart-item">
                      <div class="cart-item-details">
                        <span class="cart-item-name">{{ item.dishes.dishesName }}</span>
                        <span class="cart-item-price">￥{{ item.dishes.price }}</span>
                      </div>
                      <div class="cart-item-controls">
                        <el-button type="primary" size="mini" @click="reduceFromCart(item.dishes.id)">-</el-button>
                        <span class="item-count">{{ item.dishesCount }}</span>
                        <el-button type="primary" size="mini" @click="addToOrder(item.dishes)">+</el-button>
                      </div>
                    </el-list-item>
                  </el-list>
                </div>

                <div class="drawer-footer">
                  <div class="total-amount">总金额: ￥{{ this.totalPrice }}</div>
                  <el-button type="success" class="submit-order-button" @click="paycartToOrder">提交订单</el-button>
                  <el-button type="warn" class="submit-order-button" @click="cartClr">清空购物车</el-button>
                </div>
              </el-drawer>

              <el-button type="success" class="payment-button" @click="payOrder">支付订单</el-button>
            </div>
          </div>

          <el-dialog title="扫码支付" :visible.sync="visible" width="400px" center :close-on-click-modal="false"
            :close-on-press-escape="false">
            <img src="../assets/img/qr-code.jpg" alt="二维码" class="qr-code-image" />
          </el-dialog>

          <div class="food-display-container">
            <el-main class="food-display">
              <el-row :gutter="24">
                <el-col :span="6" v-for="(food, index) in foods" :key="index" class="food-item">
                  <div class="modern-food-card">
                    <div class="card-image-container">
                      <img :src="getImgUrl(food.imgUrl)" class="modern-food-image" alt="food image" />
                      <div class="image-overlay">
                        <div class="sales-badge">销量 {{ food.sales || 0 }}</div>
                      </div>
                    </div>
                    <div class="card-content">
                      <h4 class="food-name">{{ food.dishesName }}</h4>
                      <div class="price-section">
                        <span class="price-label">￥</span>
                        <span class="price-value">{{ food.price }}</span>
                      </div>
                      <el-button class="add-to-cart-btn" @click="addToOrder(food)">
                        <i class="el-icon-shopping-cart-2"></i>
                        加入购物车
                      </el-button>
                    </div>
                  </div>
                </el-col>
              </el-row>
            </el-main>
          </div>
        </div>
      </div>
    </el-main>
  </div>
</template>

<script>
export default {
  data () {
    return {
      searchQuery: '',
      activeTabName: 'recommend', // 控制激活的标签页
      recommendActiveIndex: '1', // 推荐分类的默认激活菜单项
      newActiveIndex: '2', // 最新分类的默认激活菜单项
      hotActiveIndex: '3', // 热门分类的默认激活菜单项
      foods: [],
      cart: [],
      isCartVisible: false,
      isLoggedIn: false, // 假设已登录
      isPerson: false,
      username: '',
      totalPrice: 0,
      visible: false,
      recommend: 1,
      status: 1
    }
  },
  beforeMount () {
    this.handleSelect('recommend', 1)
  },
  mounted () {
    this.isLogged()
  },
  methods: {

    async handleSelect (tabName, event) {
      let cod
      const index = event
      this.status = event
      if (tabName === 'recommend') {
        cod = 1
        this.recommend = 1
      } else if (tabName === 'new') {
        cod = 2
        this.recommend = 2
      } else if (tabName === 'hot') {
        cod = 3
        this.recommend = 3
      }
      const res = await this.$http.get('/dishes/cod/' + cod + '/index/' + index)
      if (res.code === 200) {
        // this.$message.success('查询成功')
        this.foods = res.data
      } else {
        this.$message.error('查询失败')
      }
    },
    async isLogged () {
      const token = localStorage.getItem('token')
      if (token) {
        this.isLoggedIn = true
        this.isPerson = true
        const res = await this.$http.get('/user/token')
        if (res.code === 200) {
          this.username = res.data.username
        } else {
          this.$message.error('获取用户信息失败')
        }
      } else {
        this.$message.error('请先登录')
      }
    },
    LoginOut () {
      localStorage.removeItem('token')
      this.isLoggedIn = false
      this.isPerson = false
      this.username = ''
      window.location.reload()
    },
    goToLogin () {
      this.$router.push({
        name: 'Login'
      })
    },
    goToAdmin () {
      this.$router.push({
        name: 'manage'
      })
    },
    async search () {
      const res = await this.$http.post('/dishes/search', {
        dishesName: this.searchQuery
      })
      if (res.code === 200) {
        this.$message.success('查询成功')
        this.foods = res.data
      } else {
        this.$message.error('查询失败')
      }
    },
    async resetSearch () {
      this.searchQuery = ''
      // 恢复到当前选中的分类数据
      await this.handleSelect(this.activeTabName, this.status)
      this.$message.success('已重置搜索')
    },
    async addToOrder (food) {
      const res = await this.$http.post('/cart/add/' + food.id)
      if (res.code === 200) {
        this.$message.success('加入购物车成功')
        const res = await this.$http.get('/cart/list')
        if (res.code === 200) {
          this.getAllCount()
          this.cart = res.data
        } else {
          this.$message.error('查询购物车失败')
        }
      } else {
        this.$message.error('加入购物车失败')
      }
    },
    async toggleCart () {
      this.isCartVisible = !this.isCartVisible
      const res = await this.$http.get('/cart/list')
      if (res.code === 200) {
        this.getAllCount()
        this.cart = res.data
      } else {
        this.$message.error('查询购物车失败')
      }
    },
    async reduceFromCart (dishesId) {
      // 找到对应的商品项
      const cartItem = this.cart.find(item => item.dishes.id === dishesId)

      if (cartItem && cartItem.dishesCount === 1) {
        // 如果数量为1，直接删除整个商品
        const res = await this.$http.delete('/cart/reduce/' + dishesId)
        if (res.code === 200) {
          this.$message.success('商品已删除')
        } else {
          this.$message.error('删除失败')
        }
      } else {
        // 如果数量大于1，正常减少数量
        const res = await this.$http.delete('/cart/reduce/' + dishesId)
        if (res.code === 200) {
          this.$message.success('减少成功')
        } else {
          this.$message.error('减少失败')
        }
      }
      // 重新获取购物车列表和总价
      const cartRes = await this.$http.get('/cart/list')
      if (cartRes.code === 200) {
        this.cart = cartRes.data
        this.getAllCount()
      }
    },

    payOrder () {
      this.visible = true
    },
    goToPerson () {
      this.$router.push('/Person')
    },
    async paycartToOrder () {
      const res = await this.$http.post('/order/addCart')
      if (res.code === 200) {
        this.$message.success('提交订单成功')
        this.cart = []
        this.totalPrice = 0
        this.isCartVisible = !this.isCartVisible
      } else {
        this.$message.error('提交订单失败')
      }
    },
    async getAllCount () {
      const res = await this.$http.get('/cart/total')
      if (res.code === 200) {
        this.totalPrice = res.data
      } else {
        this.$message.error('计算失败')
      }
    },
    async cartClr () {
      const res = await this.$http.delete('/cart/clear')
      if (res.code === 200) {
        this.$message.success('清空购物车成功')
        this.cart = []
        this.totalPrice = 0
      } else {
        this.$message.error('清空购物车失败')
      }
    },
    getImgUrl (url) {
      if (!url) return require('@/assets/img/food.jpg')

      if (url.startsWith('http://') || url.startsWith('https://')) {
        return url
      } else if (url.startsWith('/')) {
        return '/api' + url
      } else {
        try {
          return require('@/assets/img/' + url)
        } catch (e) {
          return require('@/assets/img/food.jpg')
        }
      }
    }
  }
}

</script>

<style scoped>
  body {
    background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
    margin: 0;
    padding: 0;
    font-family: Arial, sans-serif;
    min-height: 100vh;
  }

  .header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
    box-shadow: 0 4px 12px rgba(102, 126, 234, 0.2);
  }

  .header-content {
    display: flex;
    align-items: center;
    width: 100%;
    justify-content: space-between;
  }

  .title {
    font-size: 24px;
    font-weight: bold;
    text-align: center;
    margin-left: 280px;
    flex: 1;
    color: white;
    text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
  }

  .user-actions {
    display: flex;
    align-items: center;
  }

  .login-button {
    background-color: #409eff;
    color: white;
    margin-right: 10px;
  }

  .content {
    background-color: #aec6f7;
    display: flex;
    padding: 20px;
    border-radius: 8px;
  }

  .categories {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-right: none;
    border-radius: 15px;
    margin: 10px;
    box-shadow: 0 8px 32px rgba(102, 126, 234, 0.3);
    overflow: hidden;
  }

  .category-header {
    padding: 20px 15px;
    text-align: center;
    background: rgba(255, 255, 255, 0.1);
    backdrop-filter: blur(10px);
  }

  .category-title {
    color: white;
    margin: 0;
    font-size: 18px;
    font-weight: 600;
    text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
  }

  .custom-tabs {
    background: transparent;
  }

  .custom-tabs .el-tabs__nav {
    background: transparent;
  }

  .custom-tabs .el-tabs__item {
    color: rgba(255, 255, 255, 0.8);
    font-weight: 500;
    padding: 15px 12px;
    border: none;
    background: transparent;
    transition: all 0.3s ease;
    white-space: nowrap;
    overflow: visible;
    min-width: auto;
    width: auto;
  }

  .custom-tabs .el-tabs__item:hover {
    color: white;
    background: rgba(255, 255, 255, 0.1);
  }

  .custom-tabs .el-tabs__item.is-active {
    color: white;
    background: rgba(255, 255, 255, 0.2);
    border-radius: 8px;
  }

  .custom-menu {
    background: transparent;
    border: none;
  }

  .menu-item-modern {
    color: rgba(255, 255, 255, 0.9) !important;
    font-weight: 500;
    padding: 12px 15px !important;
    margin: 5px 8px;
    border-radius: 8px;
    transition: all 0.3s ease;
    background: transparent !important;
    border: none !important;
    white-space: nowrap;
    overflow: visible;
    text-overflow: clip;
    min-width: auto;
    width: auto;
  }

  .menu-item-modern:hover {
    background: rgba(255, 255, 255, 0.15) !important;
    color: white !important;
    transform: translateX(5px);
  }

  .menu-item-modern.is-active {
    background: rgba(255, 255, 255, 0.25) !important;
    color: white !important;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
  }

  .food-area {
    flex: 1;
    padding: 20px;
  }

  .search-and-payment {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    padding: 0 10px;
  }

  .search-bar-container {
    flex: 1;
  }

  .search-bar {
    width: 25%;
  }

  .reset-button {
    margin-left: 10px;
    background-color: #909399;
    border-color: #909399;
    color: white;
  }

  .reset-button:hover {
    background-color: #82848a;
    border-color: #82848a;
  }

  .button-container {
    display: flex;
    align-items: center;
  }

  .cart-button {
    background-color: #ffc107;
    margin-left: 10px;
  }

  .payment-button {
    background-color: #67c23a;
    margin-left: 10px;
  }

  .food-display-container {
    margin-top: 20px;
  }

  .food-display {
    background-color: #ffffff;
    padding: 20px;
    border-radius: 8px;
    border: 2px solid #000;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    min-height: 600px;
    overflow: hidden;
  }

  .food-item {
    margin-bottom: 24px;
  }

  .modern-food-card {
    background: white;
    border-radius: 16px;
    overflow: hidden;
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;
    border: 1px solid #f0f0f0;
  }

  .modern-food-card:hover {
    transform: translateY(-8px);
    box-shadow: 0 16px 40px rgba(0, 0, 0, 0.15);
  }

  .card-image-container {
    position: relative;
    overflow: hidden;
    height: 180px;
  }

  .modern-food-image {
    width: 100%;
    height: 100%;
    transition: transform 0.3s ease;
  }

  .modern-food-card:hover .modern-food-image {
    transform: scale(1.05);
  }

  .image-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(to bottom, transparent 0%, rgba(0, 0, 0, 0.1) 100%);
    display: flex;
    align-items: flex-end;
    justify-content: flex-end;
    padding: 12px;
  }

  .sales-badge {
    background: rgba(255, 255, 255, 0.9);
    color: #666;
    padding: 4px 8px;
    border-radius: 12px;
    font-size: 12px;
    font-weight: 500;
    backdrop-filter: blur(10px);
  }

  .card-content {
    padding: 20px;
  }

  .food-name {
    font-size: 16px;
    font-weight: 600;
    color: #333;
    margin: 0 0 12px 0;
    line-height: 1.4;
  }

  .price-section {
    display: flex;
    align-items: baseline;
    margin-bottom: 16px;
  }

  .price-label {
    font-size: 14px;
    color: #ff6b6b;
    font-weight: 500;
  }

  .price-value {
    font-size: 20px;
    font-weight: 700;
    color: #ff6b6b;
    margin-left: 2px;
  }

  .add-to-cart-btn {
    width: 100%;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border: none;
    color: white;
    padding: 12px;
    border-radius: 8px;
    font-weight: 500;
    transition: all 0.3s ease;
  }

  .add-to-cart-btn:hover {
    background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
  }

  .add-to-cart-btn i {
    margin-right: 6px;
  }

  .bottom-info {
    display: flex;
    justify-content: space-between;
    margin: 10px 0;
  }

  .cart-content {
    max-height: 60%;
    overflow-y: auto;
    padding: 10px;
  }

  .cart-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 0;
    border-bottom: 1px solid #e0e0e0;
  }

  .cart-item-details {
    display: flex;
    flex-direction: column;
    flex: 1;
  }

  .cart-item-controls {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .item-count {
    font-weight: bold;
    color: #333;
    min-width: 20px;
    text-align: center;
  }

  .cart-item-name {
    font-weight: bold;
    color: #333;
  }

  .cart-item-price {
    font-size: 14px;
    color: #999;
  }

  .el-drawer__body {
    padding: 20px;
    background-color: #f5f5f5;
  }

  .el-list-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 0;
  }

  .drawer-footer {
    position: absolute;
    bottom: 10%;
    width: 100%;
    justify-content: space-between;
    padding-left: 20px;
    padding-top: 10px;
    border-top: 1px solid #e0e0e0;
    background-color: #fff;
  }

  .total-amount {
    font-size: 18px;
    margin-bottom: 20px;
    font-weight: bold;
    color: #333;
  }

  .submit-order-button {
    margin-bottom: 10px;
  }

  .el-main {
    background-color: #aec6f7;
    padding: 20px;
    border-radius: 8px;
  }

  .el-aside {
    background-color: #e9eaec;
    border-radius: 8px;
    padding: 10px;
  }

  .qr-code-image {
    width: 100%;
    height: auto;
    display: block;
  }

</style>
